/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.command.phonenumber;

import apus.command.AbstractCommand;
import apus.entity.PhoneNumber;
import apus.entity.Subscriber;
import apus.exception.BusinessException;
import apus.persistence.AbstractDAO;
import apus.persistence.OrganizationDAO;
import apus.persistence.PersonDAO;
import apus.persistence.PhoneNumberDAO;
import apus.services.ServiceLocator;
import java.util.Arrays;
import java.util.List;

/**
 * The <code>UpdatePhoneNumberCommand</code> class represents command for 
 * changing information about phone number.
 * @author Maxim Vasilevsky
 * @author Roman Dyatkovsky
 * @since APUS v0.4
 * @see AbstractCommand
 */
public class UpdatePhoneNumberCommand<TypeEn extends Subscriber, TypeDAO extends AbstractDAO<TypeEn>> extends AbstractCommand {

    private Class<TypeDAO> clazz;
    private final static String PARAM_ID = "Phone number ID";
    private final static String NEW_OWNER_ID = "New owner ID";
    private final static String[] paramsNames = {PARAM_ID, NEW_OWNER_ID};

    public UpdatePhoneNumberCommand(Class<TypeDAO> clazz, String name) {
        super(name);
        this.clazz = clazz;
    }

    @Override
    public void execute() {

        int ID, subsriberID;
        String stringId = params.get(PARAM_ID);
        String strSubId = params.get(NEW_OWNER_ID);
        
        try {
            ID = Integer.parseInt(stringId);
            subsriberID = Integer.parseInt(strSubId);
        } catch (NumberFormatException e) {
            throw new BusinessException("Wrong ID format.", e);
        }

        PhoneNumberDAO phoneNumberDAO = ServiceLocator.getService(PhoneNumberDAO.class);
        AbstractDAO<TypeEn> subscriberDAO = ServiceLocator.getService(clazz);

        PhoneNumber phoneNumber = phoneNumberDAO.read(ID);
        Subscriber subscriber = subscriberDAO.read(subsriberID);
        
        if (phoneNumber==null){
            throw new BusinessException("Phone number not found");
        }
        
        if (subscriber==null){
            throw new BusinessException("Subscriber not found");
        }
        
        phoneNumber.setOwner(subscriberDAO.read(subsriberID));
        phoneNumberDAO.update(phoneNumber);
    }

    @Override
    public List<String> getParamNames() {
        return Arrays.asList(paramsNames);
    }

    public static UpdatePhoneNumberCommand getUpdatePhoneNumberOfPersonCommand() {
        return new UpdatePhoneNumberCommand(PersonDAO.class, "Update phone number of person");
    }

    public static UpdatePhoneNumberCommand getUpdatePhoneNumberOfOrganizationCommand() {
        return new UpdatePhoneNumberCommand(OrganizationDAO.class, "Update phone number of organization");
    }
}
